/*
 * To change this template, choose Tools | Templates and open the template in
 * the editor.
 */
package goodenglish.interfaces.videoplay;

import goodenglish.domain.service.media.PlaySubt;
import goodenglish.infrastructure.Config;

import java.util.logging.Level;
import java.util.logging.Logger;

import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.scene.media.MediaPlayer;
import javafx.util.Duration;

/**
 * 原来用开始时间点，但在实际中发现用开始时间点经常会有因为差一秒问题，而显错字幕，后改为按字幕个数
 * 
 * @author 关攀攀 panpan_001@126.com
 */
public class StudyListener implements ChangeListener<Duration> {

	private MediaPane mediaControl;
	private MediaPlayer mediaPlayer;
	private PlaySubt playSubt;
	// 当前学习的字幕游标
	private int subtIndex = 0;

	// 重播放间的暂停时间
	// int pauseTime = 1;

	private PlayRegion playRegion;

	public StudyListener(MediaPane mediaControl) {
		this.mediaControl = mediaControl;
		this.mediaPlayer = mediaControl.mediaPlayer;
		this.playSubt = new PlaySubt(mediaControl.subt);
		// 设定播放区间
		this.playRegion = new PlayRegion(playSubt, subtIndex, playRegion);
	}

	public void changed(ObservableValue<? extends Duration> observable, Duration oldValue, Duration newValue) {
		Duration timeDuration = mediaPlayer.getCurrentTime();
		int timeInt = (int) Math.floor(timeDuration.toMillis());
		// 如果没有学习字幕先学习字幕
		studySubt();

		controlPlay(timeInt);

	}

	private void controlPlay(final int timeInt) {

		// 如果当前时间超出了当前区间
		if (playRegion.over(timeInt)) {
			// 播放次数加一
			playRegion.addPlayNum();
			// 如果达到播放次数则敲定播放时间为下一区间
			if (playRegion.getReplayNum() == Config.PLAYLISTENER_REPLAYCOUNT) {
				// 学习下一个字幕
				subtIndex += Config.PLAYLISTENER_STEP;
				this.playRegion = new PlayRegion(playSubt, subtIndex, playRegion);
				studySubt();
			} else if (playRegion.getReplayNum() < Config.PLAYLISTENER_REPLAYCOUNT) {
				playRegion();
			}

		}
	}

	private void playRegion() {
		// 从区间开始时间重新播放
		this.mediaPlayer.seek(new Duration(playRegion.getStime()));
		this.mediaPlayer.play();
		this.mediaControl.updateValues();
	}

	private void studySubt() {
		if (playRegion.isStudyed()) {
			return;
		}

		showRegionSubt();
		playRegion.setStudyed(true);

	}

	private void showRegionSubt() {
		if (playRegion.getSentenceForPlay().subtWordCounts != 0) {
			this.mediaPlayer.pause();

			// 学习时间
			for (int i = 0; i < playRegion.getStudytime() * 10; i++) {
				StringBuffer buffer = new StringBuffer();
				buffer.append(Integer.toString(playRegion.getStudytime() - i / 10));
				buffer.append("\r\n");
				buffer.append(playRegion.getSentenceForPlay().explainStrs);
				MediaGroup.playLabel.displayForStudy(buffer.toString());
				if (playRegion.manCanceled) {
					break;
				}
				try {
					Thread.sleep(100);
				} catch (InterruptedException ex) {
					Logger.getLogger(MediaPane.class.getName()).log(Level.SEVERE, null, ex);
				}
			}
			MediaGroup.playLabel.displayForView("");
			// this.regionStime -= 10;
			playRegion();
		}
	}

}
